import {DependencyList, useCallback, useState} from 'react'
import {useIsomorphicLayoutEffect} from "ahooks";

/**
 * 获取ref元素高度
 */
function useRefHeight<T extends HTMLElement = HTMLDivElement>(deps?: DependencyList): [(node: T | null) => void, number, Function] {
    // Mutable values like 'ref.current' aren't valid dependencies
    // because mutating them doesn't re-render the component.
    // Instead, we use a state as a ref to be reactive.
    const [ref, setRef] = useState<T | null>(null)
    const [height, setHeight] = useState<number>(0)

    // Prevent too many rendering using useCallback
    const handleHeight = useCallback(() => {
        setHeight(ref?.offsetHeight || 0)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [ref?.offsetHeight])

    useIsomorphicLayoutEffect(() => {
        handleHeight()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [ref?.offsetHeight, ...deps || []])

    return [setRef, height, handleHeight]
}

export default useRefHeight
